<template>
    <div>
        <div class="search">
            <div class="search-input">
                <input type="text" class="search-input-content" placeholder="输入城市名或拼音" v-model="keyword">
            </div>
        </div>
        <div class="search-content" ref="search" v-show="keyword">
            <ul>
                <li
                    @click="handleCityClick(item.name)"
                    v-for="item of list"
                    :key="item.index"
                    class="search-item border-bottom">
                    {{item.name}}
                </li>
                <li class="search-item border-bottom" v-show="hasNoData">没有匹配到该城市</li>
            </ul>
        </div>
    </div>
</template>
<script>
import Bscroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  props: {cities: Object},
  name: 'CitySearch',
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
      this.keyword = ''
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 ||
                value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  updated () {
    this.scroll.refresh()
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search, {click: true})
  }
}
</script>
<style lang="stylus" scoped>
@import '~assets/variles.styl'
.search
    display: flex
    background: $bgColor
    height: $headerHeight
    line-height: $headerHeight
    .search-input
        width: 95%
        height: 90%
        border-radius: .10rem
        overflow: hidden
        margin:  0 auto
    .search-input-content
        width: 100%
        height: 100%
        text-align: center
        color: #666
        box-sizing: border-box
        padding: 0 .1rem
.search-content
    z-index:1
    position absolute
    top: 2*$headerHeight
    left: 0
    right: 0
    bottom: 0
    overflow: hidden
    background: #eee
    .search-item
        line-height: .62rem
        padding-left: .2rem
        color: #666
        background: #fff
</style>
